package com.cnwidsom.plugins;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.cnwidsom.config.MonitorConfig;
import com.cnwidsom.plugins.persistence.Persistence;
import com.cnwidsom.plugins.type.TypeInjector;

public class PluginUtils {
	private static Map<String, TypeInjector> typeMap = new HashMap<String, TypeInjector>();
	private static Map<String, Persistence> persistenceMap = new HashMap<String, Persistence>();
	static {
		Properties props = new Properties();
		try {
			props.load(PluginUtils.class.getResourceAsStream("/plugins.properties"));
			String typeInjectPlugins = props.get("typeInject.plugins").toString();
			for (String pluginClassName : typeInjectPlugins.split(",")) {
				try {
					Class<TypeInjector> pluginClass = (Class<TypeInjector>) Class.forName(pluginClassName);
					TypeInjector ti = pluginClass.newInstance();
					for (int i = 0; i < MonitorConfig.getCur_mc().getMonitorTypes().size(); i++) {
						if (MonitorConfig.getCur_mc().getMonitorTypes().get(i).equals(ti.getName())) {
							ti.setParameters(MonitorConfig.getCur_mc().getMonitorTypeParam().get(i));
							ti.init();
							break;
						}
					}
					typeMap.put(ti.getName(), ti);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}

			String persistencePlugins = props.get("persistence.plugins").toString();
			for (String pluginClassName : persistencePlugins.split(",")) {
				try {
					Class<Persistence> pluginClass = (Class<Persistence>) Class.forName(pluginClassName);
					Persistence ps = pluginClass.newInstance();
					ps.setParameters(MonitorConfig.getCur_mc().getPersistenceTypeParam());
					persistenceMap.put(ps.getName(), ps);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static TypeInjector getTypeInjectorByName(String name) {
		return typeMap.get(name);
	}

	public static Persistence getPersistenceByName(String name) {
		return persistenceMap.get(name);
	}
}
